Module# 10: Set                                                           Lecture#41: Operations on Set Collections

 

// Example 41.1: Creating a set with HashSet class

 

import java.util.*;

 

class HashSetCreateDemo {

     public static void main(String args[]) {

      // Create a hash set.

      HashSet<String>hs = new HashSet<String>();

      // Set<String>hs = new HashSet<String>();

 

      // Add elements to the hash set.

      hs.add("India");

      hs.add("Japan");

      hs.add("Australia");

      hs.add("Bangladesh");

      hs.add("Pakistan");

      hs.add("Nepal");

      System.out.println(hs);

     }

}

 

 

// Example 41.2: Adding a duplicate object

 

/* The following program illustrates that if you add an object, which is already in the set, then that inclusion will be ignored automatically. */

 

import java.util.HashSet;

import java.util.Set;

 

public class HashSetDuplicateDemo {

    public static void main(String[] args) {

        // Creating a HashSet

        Set<String>daysOfWeek = new HashSet<>();

 

        // Adding new elements to the HashSet

        daysOfWeek.add("Monday");

        daysOfWeek.add("Tuesday");

        daysOfWeek.add("Wednesday");

        daysOfWeek.add("Thursday");

        daysOfWeek.add("Friday");

        daysOfWeek.add("Saturday");

        daysOfWeek.add("Sunday");

 

        // Adding duplicate elements will be ignored

        daysOfWeek.add("Monday");

 

        System.out.println(daysOfWeek);

    }

}

 

 

// Example 41.3: Creating a set from a collection

 

import java.util.*;

 

class HashSetCollectionDemo {

     public static void main(String args[]) {

      //Creating a hash set from a collection

      List<Integer> list = Arrays.asList(3, 9, 2, 4, 6, 2, 5, 3, 8, 9, 1, 7, 8, 6);

      System.out.println(listNumbers);

 

      HashSet<Integer>numSet = newHashSet<>(list);

      System.out.println(numSet);

 

      Set<Integers>bigSet = newHashSet<>(1000);

      for(inti = 0; i< 1000, i++)

           bigSet.add(Math.Random());

          System.out.printn(“If 555 is in the bigSet?+bigSet.contains(555));

     }

}

 

 

// Example 41.4: Traversing a set using Iterator

 

import java.util.*;

 

public class SetTraversalDemo {

    public static void main(String[] args) {

      Set<String>pLangs = new HashSet<>();

      pLangs.add("C");

pLangs.add("C++");

pLangs.add("Java");

pLangs.add("Python");

pLangs.add("PHP");

pLangs.add("R");

 

      // Using simple for-each loop

      for(String pl: pLangs) {

          System.out.println(pl);

          }

 

// Using iterator()

Iterator<String>iter = pLangs.iterator();

while (iter.hasNext()) {

             String pl = iter1.next();

      System.out.println(pl);

      }

 

// Using forEach and lambda expression

pLangs.forEach(pLangs ->{ System.out.println(pLangs); });

 

// Using iterator() and forEachRemaining() method

iter = pLangs.iterator();

iter.forEachRemaining(pLangs -> { System.out.println(pLangs); });

       }

}

 

 

// Example 41.5: Traversing a set using for and Lambda-expression

 

/* The following program demonstrates a number of ways to traversing a HashSet collection. */

 

import java.util.*;

 

class HashSetTraversalDemo {

     public static void main(String args[]) {

      // Create a hash set.

Set<String> names = new HashSet<>();

names.add("Tom");

names.add("Mary");

names.add("Tom");

names.add("John");

names.add("Tom");

names.add("Bob");

names.add("Alice");

 

// Using a for loop

for (String name : names) {

            System.out.println(name);

}

 

      // Uisngforeach method along with Lambda expression

      names.forEach(System.out::println);

     }

}

 

 

// Example 41.6: Basic set theory operation

 

/* The following program demonstrates searching operation with a HashSet collection. */

 

import java.util.*;

 

class HashSetOperationDemo3 {

     public static void main(String args[]) {

// Create a hash set.

Set<Integer> s1 = new HashSet<>(Arrays.asList(20, 56, 89, 31, 8, 5));

Set<Integer> s2 = new HashSet<>(Arrays.asList(8, 89));

 

// Sub set operation

if (s1.containsAll(s2)) {

       System.out.println("s2 is a subset of s1");

}

 

// Union operation

Set<Integer> s3 = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9));

Set<Integer> s4 = new HashSet<>(Arrays.asList(2, 4, 6, 8));

 

System.out.println("s3 before union: " + s4);

S3.addAll(s4);

System.out.println("s3 after union: " + s4);

 

// Intersection operation

Set<Integer> s5 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));

Set<Integer> s6 = new HashSet<>(Arrays.asList(2, 4, 6, 8));

 

System.out.println("s5 before intersection: " + s6);

s5.retainAll(s6);

System.out.println("s5 after intersection: " + s6);

 

// Set difference operation

Set<Integer> s7 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));

Set<Integer> s8 = new HashSet<>(Arrays.asList(2, 4, 6, 8));

 

System.out.println("s7 before difference: " + s8);

s7.removeAll(s8);

System.out.println("s7 after difference: " + s8);

        }  

 }

 

 

// Example 41.7: Difference between HashSet and LinkedHashSet

/* The following program illustrates the ordering of elements in two sets created by Hashset and LinkedHashset classes. */

 

import java.util.*;

 

class DifferentSetDemo {

     public static void main(String args[]) {

// Create a hash set.

HashSet<String>hs = new HashSet<String>();

 

// Add elements to the hash set.

hs.add("A");

hs.add("B");

hs.add("C");

hs.add("D");

hs.add("E");

hs.add("F");

System.out.println(hs);

 

// Create a linked hash set.

LinkedHashSet<String>lhs = new LinkedHashSet<String>();

 

// Add elements to the hash set.

lhs.add("A");

lhs.add("B");

lhs.add("C");

lhs.add("D");

lhs.add("E");

lhs.add("F");

System.out.println(lhs);

      }

}

 

// Example 41.8: Creating a TreeSet collection

 

/* The following program illustrates the creating a tree sets created by TreeSet class. */

 

import java.util.*;

 

class TreeSetDemo {

     public static void main(String args[]) {

// Create a tree set.

TreeSet<String>ts = new TreeSet<String>();

 

// Add elements to the tree set.

ts.add("D");

ts.add("E");

ts.add("B");

ts.add("A");

ts.add("S");

ts.add("I");

ts.add("S");

System.out.println(ts);

      }

}

 

// Example 41.9: Sub set of a TreeSet collection

 

/* Because TreeSet implements the NavigableSet interface, you can use the methods defined by NavigableSet to retrieve elements of a TreeSet .You can write many programs performing several operations with the method declared in NavigableSet. In the following, the application of subSet() is illustrated. The subSet() method returns a sub set of a tree set that contains the elements between elements, say e1 (inclusive) and e2 (exclusive).

*/

 

import java.util.*;

 

class SubSetTreeSetDemo {

     public static void main(String args[]) {

// Create a tree set.

TreeSet<String>ts = new TreeSet<String>();

 

// Add elements to the tree set.

ts.add("D");

ts.add("E");

ts.add("B");

ts.add("A");

ts.add("S");

ts.add("I");

ts.add("S");

System.out.println(ts.subSet(“D”, “S”);

       }

}

 

// Example 41.10: Set collection of user defined objects

 

import java.util.HashSet;

import java.util.Objects;

import java.util.Set;

 

class Customer {

    private long id;

    private String name;

    public Customer(long id, String name) {

        this.id = id;

        this.name = name;

    }

    public long getId() {

        return id;

    }

    public void setId(long id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

 

// Two customers are equal if their IDs are equal

    @Override

    public booleanequals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Customer customer = (Customer) o;

        return id == customer.id;

    }

 

    @Override

    public inthashCode() {

        return Objects.hash(id);

    }

 

    @Override

    public String toString() {

        return "Customer{" +

                "id=" + id +

                ", name='" + name + '\'' +

                '}';

    }

}

 

public class HashSetUserDefinedObjectExample {

        public static void main(String[] args) {

            Set<Customer> customers = new HashSet<>();

customers.add(new Customer(101, "Rajeev"));

customers.add(new Customer(102, "Sachin"));

customers.add(new Customer(103, "Chris"));

 

             /*

HashSet will use the `equals()` & `hashCode()` implementations

            of the Customer class to check for duplicates and ignore them

            */

customers.add(new Customer(101, "Rajeev"));

 

System.out.println(customers);

      }

}